//
//  LZRegisterViewController.m
//  laziz_Consumer
//
//  Created by ZhaoDongBo on 2016/10/24.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZRegisterViewController.h"

#import "LZLoginButtonView.h"
#import "LZLoginTextFieldView.h"

#import "UIViewController+NavigationItemSetting.h"
#import "UIView+Rotation.h"
#import "UIButton+EnlargeEdge.h"
#import "NSString+LZRegex.h"
#import "GVUserDefaults+LZLogin.h"

#import "LZTextField.h"

#import "Masonry.h"
#import "TShareEventHandler.h"
#import "LZUserModel.h"
#import "GVUserDefaults+LZProperties.h"
#import "LZRemindView.h"
#import "LZNotificationPresenter.h"
#import "LZUserInfoPresenter.h"
#import "LZCommonWebViewController.h"
#import "LZAreaCodeViewController.h"
#import "LZLoginViewController.h"
#import "LZAlertView.h"

typedef NS_ENUM(NSInteger ,RegisterType) {
    RegisterType_Phone,
    RegisterType_Mail
};

@interface LZRegisterViewController ()

@property (nonatomic, assign) RegisterType type;

@property (nonatomic, strong) UIImageView * bgImageView;
@property (nonatomic, strong) UIImageView * logoImageView;
@property (nonatomic, strong) LZLoginTextFieldView * registerByPhoneView;
@property (nonatomic, strong) LZLoginTextFieldView * registerByMailView;
@property (nonatomic, strong) LZLoginButtonView * loginButtonView;

@property (strong, nonatomic) UIButton *nav_left_back;
@property (strong, nonatomic) UIButton *nav_right_button;
@property (assign, nonatomic) CGFloat lzAlpha;
@property (nonatomic, strong) LZUserInfoPresenter * userInfoPresenter;

@property (nonatomic, strong) NSTimer * timer;      //验证码倒计时
@property (nonatomic, assign) int count;
@property (nonatomic, assign) BOOL agreeServiceAgreement; //标记是否同意了服务协议

@end

@implementation LZRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.umLogPageViewName = @"注册页面";
    
    self.lzAlpha = 0;
    
    self.type = RegisterType_Phone;
    
    self.userInfoPresenter = [[LZUserInfoPresenter alloc] init];
    
    
    [self configViews];
    
    [self configAutoLayout];
    
    [self configNavigationBar];
    
    
    WS(weakSelf);
    
    self.registerByPhoneView.buttonAction_TF_Block = ^(LZLOGIN_TF_BUTTON_TAG buttonTag) {
        
        if (buttonTag == LZLOGIN_TF_BUTTON_TAG_VERIFICCODE) {
            
            [weakSelf getVerifiCode];
        }
        else if (buttonTag == LZLOGIN_TF_BUTTON_TAG_AGREEMENT) {
            DLog(@"阅读协议");
            LZCommonWebViewController *Vc = [[LZCommonWebViewController alloc]init];
            Vc.webCode = kWebState_service;
            [weakSelf.navigationController pushViewController:Vc animated:YES];
        }
    };
    
    self.loginButtonView.buttonActionBlock = ^(LZLOGINBUTTONTYPE_TAG buttonTag) {
        
        if (buttonTag == LZLOGINBUTTONTYPE_TAG_REGISTER) {
            DLog(@"注册按钮事件");
            [weakSelf registerAction];
        }
        else if (buttonTag == LZLOGINBUTTONTYPE_TAG_REGISTERBYTYPE) {
            DLog(@"切换注册方式事件");
            if (weakSelf.type == RegisterType_Phone) {
                weakSelf.type = RegisterType_Mail;
                [weakSelf.loginButtonView.registerByTypeButton setTitle:LZLocalizedString(@"register_by_mobile", nil) forState:UIControlStateNormal];
                weakSelf.registerByPhoneView.hidden = YES;
                weakSelf.registerByMailView.hidden = NO;
            }
            else if (weakSelf.type == RegisterType_Mail) {
                weakSelf.type = RegisterType_Phone;
                [weakSelf.loginButtonView.registerByTypeButton setTitle:LZLocalizedString(@"register_by_email", nil) forState:UIControlStateNormal];
                weakSelf.registerByPhoneView.hidden = NO;
                weakSelf.registerByMailView.hidden = YES;
            }
        }
    };
    
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc {

    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (BOOL)fd_prefersNavigationBarHidden {
    return YES;
}
#pragma mark - Private method

- (void)configNavigationBar {
    
    self.nav_left_back = [UIButton buttonWithType:UIButtonTypeCustom];
    self.nav_left_back.frame = CGRectMake(0, 0, 60, 40);
    [self.nav_left_back addTarget:self action:@selector(navbarBackButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
    UIImage *image_back = [UIImage imageNamed:@"lz_back"];
    [self.nav_left_back setImage:image_back forState:UIControlStateNormal];
    self.nav_left_back.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, CGRectGetWidth(self.nav_left_back.bounds)-image_back.size.width);
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {
        [self.nav_left_back setLanguageRotaion];
    }
    
    self.nav_right_button = [UIButton buttonWithType:UIButtonTypeCustom];
    self.nav_right_button.frame = CGRectMake(0, 0, 80, 40);
    self.nav_right_button.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.nav_right_button setTitle:LZLocalizedString(@"login_for_restaurants", nil) forState:UIControlStateNormal];
    [self.nav_right_button setTitleColor:UIColorFromRGB(0xcccccc, 1) forState:UIControlStateNormal];
    [self.nav_right_button sizeToFit];
    self.nav_right_button.frame = CGRectMake(0, 0, CGRectGetWidth(self.nav_right_button.bounds)+15, self.nav_right_button.titleLabel.intrinsicContentSize.height + 5);
    self.nav_right_button.backgroundColor = UIColorFromRGB(0x000000, 0.2);
    self.nav_right_button.layer.cornerRadius = CGRectGetHeight(self.nav_right_button.bounds)/2.0;
    self.nav_right_button.layer.masksToBounds = YES;
    
    [self.nav_right_button addTarget:self action:@selector(navbarRegisterButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.nav_right_button setEnlargeEdgeWithTop:10 right:0 bottom:10 left:0];
    
    [self hiddenBarNavigationItemSetting:@[self.nav_left_back] type:NAVIGATIONITEMSETTING_LEFT];
    [self hiddenBarNavigationItemSetting:@[self.nav_right_button] type:NAVIGATIONITEMSETTING_RIGHT];

    [self lz_setCustomBarAlpha:self.lzAlpha];
}

- (void)configViews {
    
    [self.view addSubview:self.bgImageView];
    [self.view addSubview:self.logoImageView];
    [self.view addSubview:self.registerByPhoneView];
    [self.view addSubview:self.registerByMailView];
    [self.view addSubview:self.loginButtonView];

    self.agreeServiceAgreement = YES;
}

- (void)configAutoLayout {
    
    GET_SCREEN_SCALE(scale);
    
    [self.logoImageView makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(113.0*scale);
        make.centerX.equalTo(0);
    }];
    
    [self.registerByPhoneView makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.view.centerY);
        make.leading.mas_equalTo(0);
        make.trailing.mas_equalTo(0);
        make.height.mas_equalTo(230.0*scale);
    }];
    
    [self.registerByMailView makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.view.centerY);
        make.leading.mas_equalTo(0);
        make.trailing.mas_equalTo(0);
        make.height.mas_equalTo(230.0*scale);
    }];
    
    [self.loginButtonView makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view.mas_bottom);
        make.leading.mas_equalTo(0);
        make.trailing.mas_equalTo(0);
        make.height.mas_equalTo(55.0*scale*2);
    }];
}

- (void)getVerifiCode {
    
    if (self.registerByPhoneView.mobileNumTextField.text.length <= 0) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                         andContent:LZLocalizedString(@"login_enter_mobile", @"")];
        return;
    }
    //验证码类型（1注册，2快捷登录，3身份验证，4绑定手机）
    NSString * mobileStr = [NSString stringWithFormat:@"%@%@",
                            self.registerByPhoneView.areaCodeTextField.text,
                            self.registerByPhoneView.mobileNumTextField.text];
    
    
    
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    
    WS(weakSelf);
    
    [self.userInfoPresenter userGetVerificationCodeType:@"1"
                                            andPhoneNum:mobileStr
                                              onSuccess:^(id data) {
                                                  NSLog(@"注册 -（1）- 获取验证码:%@", data);
                                                  
                                                  [weakSelf stopLoadingViewForView:weakSelf.view];
                                                  //显示倒计时
                                                  [weakSelf startTimer];
                                                  
                                              } onFail:^(NSString *fail) {
                                                  DLog(@"%@", fail);
                                                  [weakSelf stopLoadingViewForView:weakSelf.view];

                                                  if ([fail isEqualToString:@"9999999"]) {
                                                      
//                                                      [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
//                                                                       andContent:LZLocalizedString(@"send_code_maxnum_remind", nil)];
                                                      LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"send_code_maxnum_remind", nil)
                                                                                                       andImage:[UIImage imageNamed:@"error_image"]
                                                                                              cancelButtonTitle:LZLocalizedString(@"confirm", nil)
                                                                                              otherButtonTitles:nil, nil];
                                                      [alert show];
                                                  }
                                                  else {
                                                      
                                                      [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                                                                       andContent:LZLocalizedString(@"vificode_failed", nil)];
                                                  }
                                                  
                                              }];
}

- (void)registerAction {
    
    if (self.agreeServiceAgreement == NO) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                         andContent:LZLocalizedString(@"read_and_agree_service", @"")];
        return;
    }
    
    NSString * userName = nil;
    NSString * email = nil;
    NSString * verifiCode = nil;
    NSString * passwordStr = nil;
    
    if (self.type == RegisterType_Phone) {
        
        userName = [NSString stringWithFormat:@"%@%@",
                    self.registerByPhoneView.areaCodeTextField.text,
                    self.registerByPhoneView.mobileNumTextField.text];
        
        verifiCode = self.registerByPhoneView.verificCodeTextField.text;
        
        passwordStr = self.registerByPhoneView.passwordTextField.text;

        if (self.registerByPhoneView.mobileNumTextField.text.length <= 0) {
            [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                             andContent:LZLocalizedString(@"login_enter_mobile", @"")];
            return;
        }
        else if (verifiCode.length <= 0) {
            [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                             andContent:LZLocalizedString(@"login_enter_verifi_code", @"")];
            return;
        }
        else if (passwordStr.length <= 0) {
            [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                             andContent:LZLocalizedString(@"enter_password", @"")];
            return;
        } else if (passwordStr.length > 0 && passwordStr.length < 6) {
            [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                             andContent:LZLocalizedString(@"enter_password_6_chart", @"")];
            return;
        }
        
        DLog(@"userName: %@", userName);
        DLog(@"passwordStr: %@", passwordStr);
        
        [self stopTimer];
    }
    else if (self.type == RegisterType_Mail) {
        email = self.registerByMailView.mobileNumTextField.text;
        passwordStr = self.registerByMailView.passwordTextField.text;
        
        
        if (email.length <= 0) {
            [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                             andContent:LZLocalizedString(@"login_enter_email", nil)];
        }
        else if (passwordStr.length <= 0) {
            [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                             andContent:LZLocalizedString(@"enter_password", @"")];
            return;
        } else if (passwordStr.length > 0 && passwordStr.length < 6) {
            [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                             andContent:LZLocalizedString(@"enter_password_6_chart", @"")];
            return;
        }
        else if (![email isEmailAddress]) {
            [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                             andContent:LZLocalizedString(@"invalid_email_remind", nil)];
            return;
        }
    }
    
    
    
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    
    WS(weakSelf);
    [self.userInfoPresenter userRegisterCellPhone:userName
                                         andEmail:email
                                      andPassword:passwordStr
                              andVerificationCode:verifiCode
                                     andonSuccess:^(id data) {
                                         
                                         DLog(@"%@", data);
                                         
                                         [weakSelf stopLoadingViewForView:weakSelf.view];
                                         
                                         if (weakSelf.type == RegisterType_Phone) {
                                             // 记录选择的区号
                                             [GVUserDefaults standardUserDefaults].loginAreaCode = weakSelf.registerByPhoneView.areaCodeTextField.text;
                                             
                                             // 记录登录方式，用于下次登录时显示对应的UI
                                             [GVUserDefaults standardUserDefaults].loginType = [NSString stringWithFormat:@"%ld",(long)LoginType_Phone];

                                         }
                                         else if (self.type == RegisterType_Mail) {
                                             // 记录登录方式，用于下次登录时显示对应的UI
                                             [GVUserDefaults standardUserDefaults].loginType = [NSString stringWithFormat:@"%ld",(long)LoginType_Mail];

                                         }
                                         
                                         
                                         [[GVUserDefaults standardUserDefaults] setUserToken:[[data objectForKey:@"data"] objectForKey:@"token"]];
                                         [LZNotificationPresenter setNotificationAlias:[[data objectForKey:@"data"] objectForKey:@"userId"]];
                                         [[GVUserDefaults standardUserDefaults] setUserId:[[data objectForKey:@"data"] objectForKey:@"userId"]];
                                         
                                         //否则跳转个人页面
                                         [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                                         
                                     } onFail:^(NSString *fail) {
                                         
                                         DLog(@"%@", fail);
                                         
                                         [weakSelf stopLoadingViewForView:weakSelf.view];
                                         
                                         if ([fail isEqualToString:@"0400001"] || [fail isEqualToString:@"0100010"] || [fail isEqualToString:@"0500001"]) {//0500001 验证码错误
                                             [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                                                              andContent:LZLocalizedString(@"enter_invalid_verifi", nil)];
                                         }
                                         else if ([fail isEqualToString:@"0500004"]) { //0500004 当前手机号已经被注册
                                             [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"phone_is_register", @"")]; //0400004 当前手机号已经被注册
                                         }
                                         else if ([fail isEqualToString:@"0400039"]) { //0400039 当前邮箱已经被注册
                                             [LZRemindView initWithImage:[UIImage imageNamed:@"错误提示"] andContent:LZLocalizedString(@"email_is_register", @"")]; //0400004 当前手机号已经被注册
                                         }
                                         else {
                                             [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                                                              andContent:LZLocalizedString(@"register_failed", nil)];
                                         }
                                     }];
}

#pragma mark - Event

- (void)navbarBackButtonClickAction:(UIButton*)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)navbarRegisterButtonClickAction:(UIButton*)sender {
    DLog(@"跳转 appStore 按钮");
    
    [TShareEventHandler jumpToAppstoreForMerchantApp];
}

- (void)startTimer {

    self.registerByPhoneView.countdownLabel.text = @"60s";
    [self.timer invalidate];
    self.count = 0;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                  target:self
                                                selector:@selector(updateTime)
                                                userInfo:nil
                                                 repeats:YES];
    
    self.registerByPhoneView.countdownLabel.hidden = NO;
    self.registerByPhoneView.verificCodeButton.hidden = YES;
}

- (void)stopTimer {
    [self.timer invalidate];
    self.registerByPhoneView.countdownLabel.hidden = YES;
    self.registerByPhoneView.verificCodeButton.hidden = NO;
}

- (void)updateTime
{
    self.count ++;
    if (self.count >= 60)
    {
        [self stopTimer];
        return;
    }
    
    self.registerByPhoneView.countdownLabel.text = [NSString stringWithFormat:@"%is", 60-self.count];
    
    if (self.count == 60) {
        self.registerByPhoneView.countdownLabel.hidden = YES;
        self.registerByPhoneView.verificCodeButton.hidden = NO;
    }
}


#pragma mark - Setter/Getter

- (void)setAgreeServiceAgreement:(BOOL)agreeServiceAgreement {
    _agreeServiceAgreement = agreeServiceAgreement;
    self.registerByPhoneView.selectButton.selected = agreeServiceAgreement;
    self.registerByMailView.selectButton.selected = agreeServiceAgreement;
}

- (UIImageView *)bgImageView {
    
    if (_bgImageView == nil) {
        _bgImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
        _bgImageView.image = [UIImage imageNamed:@"lz_bg"];
    }
    
    return _bgImageView;
}

- (UIImageView *)logoImageView {
    if (_logoImageView == nil) {
        _logoImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"lz_logo_white"]];
    }
    return _logoImageView;
}

- (LZLoginTextFieldView *)registerByPhoneView {
    
    if (_registerByPhoneView == nil) {
        _registerByPhoneView = [[LZLoginTextFieldView alloc] initWithPage:LZLOGIN_TF_TYPE_PAGE_REGISTER_PHONE];
        
        WS(weakSelf);
        
        _registerByPhoneView.clickAreaCodeTextFieldBlock = ^(UILabel *label) {
            LZAreaCodeViewController *vc = [[LZAreaCodeViewController alloc] init];
            [weakSelf.navigationController pushViewController:vc animated:YES];
            vc.SelectedAreaCodeBlock = ^(NSString *areaCode) {
                label.text = areaCode;
            };
        };
        
        _registerByPhoneView.clickAgreementButtonBlock = ^(BOOL isAgree) {
            weakSelf.agreeServiceAgreement = isAgree;
        };
    }

    return _registerByPhoneView;
}

- (LZLoginTextFieldView *)registerByMailView {
    
    if (_registerByMailView == nil) {
        _registerByMailView = [[LZLoginTextFieldView alloc] initWithPage:LZLOGIN_TF_TYPE_PAGE_REGISTER_MAIL];
        _registerByMailView.hidden = YES;
        
        WS(weakSelf)
        _registerByMailView.clickAgreementButtonBlock = ^(BOOL isAgree) {
            weakSelf.agreeServiceAgreement = isAgree;
        };
    }
    
    return _registerByMailView;
}

- (LZLoginButtonView *)loginButtonView {
    
    if (_loginButtonView == nil) {
        _loginButtonView = [[LZLoginButtonView alloc] initWithPage:LZLOGINBUTTONTYPE_PAGE_REGISTER];
        [_loginButtonView.registerByTypeButton setTitle:LZLocalizedString(@"register_by_email", nil) forState:UIControlStateNormal];
    }
    
    return _loginButtonView;
}

@end
